package com.llxwz.controller;


import com.llxwz.entity.DiscussPost;
import com.llxwz.entity.Page;
import com.llxwz.entity.Tag;
import com.llxwz.entity.User;
import com.llxwz.service.DiscussPostService;
import com.llxwz.service.LikeService;
import com.llxwz.service.TagService;
import com.llxwz.service.UserService;
import com.llxwz.util.CommunityConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class IndexController implements CommunityConstant {

    @Autowired
    DiscussPostService discussPostService;

    @Autowired
    UserService userService;

    @Autowired
    private LikeService likeService;

    @Autowired
    private TagService tagService;

    @GetMapping({"/index","/"})
    public String showDiscussPost(Model model, Page page){

        page.setRows(discussPostService.findDiscussPostRows(0));
        page.setPath("/index");

        List<DiscussPost> discussPosts = discussPostService.findDiscussPosts(0,page.getCurrent(),page.getLimit());
        List<Map<String,Object>> result = new ArrayList<>();
        if(discussPosts != null){
            for(DiscussPost discussPost:discussPosts){
                Map<String,Object> map = new HashMap<>();
                map.put("post",discussPost);
                User user = userService.findById(discussPost.getUserId());
                map.put("user",user);

                Tag tag = tagService.findTagById(discussPost.getTagId());
                map.put("tag",tag);

                long likeCount = likeService.findEntityLikeCount(ENTITY_TYPE_POST,discussPost.getId());
                map.put("likeCount",likeCount);

                result.add(map);
            }
        }

        List<Tag> tags = tagService.findTags(ENTITY_TYPE_POST,0);
        model.addAttribute("tags",tags);

        model.addAttribute("result",result);
        return "index";
    }


    @GetMapping("/error")
    public String getErrorPage(){
        return "error/500";
    }

    //跳转没有权限的页面
    @GetMapping("/denied")
    public String getDeniedPage() {
        return "error/404";
    }


}
